<template>
  <receipt-core
    @clear-open-json="clearOpenJson"
    @pose-edit-json="poseEditJson"
    @pose-submit-json="poseSubmitJson"
    @add-row-sub="addRowSub"
    @data-format="dataFormat"
    @delete-row-sub="deleteRowSub"
    @json-format="jsonFormat"
    ref="idJsonItemsRefs"
    receipts-name="patch_order_plan_receipt"
    receipts-type="补片生产计划编制"
    receipts-no="010"
  >
    //弹窗的主表的插入的idJson信息
    <template #idJsonSlot>
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="所补生产计划名称："
            prop="productionPlanNo"
            label-width="200"
          >
            <autocomplete-input
              v-model="idJsonItems.productionPlanName"
              :value-key="selectedPropMap.selectedOriginProp"
              @get-record="getRecords"
              @change="
                setSelectRow(
                  selectedPropMap.setProp,
                  selectedPropMap.setOriginProp,
                  selectedPropMap.selectedProp
                )
              "
              @select="
                setSelectRow(
                  selectedPropMap.setProp,
                  selectedPropMap.setOriginProp,
                  selectedPropMap.selectedProp
                )
              "
            ></autocomplete-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="所补生产计划编码："
            prop="productionPlanName"
            label-width="200"
          >
            <el-input
              v-model="idJsonItems.productionPlanNoHand"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划日期：" prop="plannedDate">
            <el-date-picker
              v-model="idJsonItems.plannedDate"
              type="date"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="计划总个数：" prop="planNumber">
            <el-input v-model="idJsonItems.planNumber"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="编制人：" prop="preparationPerson">
            <el-input v-model="idJsonItems.preparationPerson"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="编制时间：" prop="preparationDate">
            <el-date-picker
              v-model="idJsonItems.preparationDate"
              type="date"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    //弹窗的子表的表格的插入的subJson信息
    <template #subJson>
      <el-table-column label="类型" width="160" min-width="160">
        <template #default="scope">
          <el-input
            v-model="subJsonItems[scope.$index].category"
            disabled
            placeholder="补片"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" min-width="180">
        <template #default="scope">
          <autocomplete-input
            v-model="subJsonItems[scope.$index].materialNo"
            :value-key="selectedPropMapSub.selectedOriginProp"
            @get-record="autocompleteInputEventSub.getRecords"
            @change="
              setSelectRowData(
                selectedPropMapSub.setProp,
                selectedPropMapSub.setOriginProp,
                selectedPropMapSub.selectedProp,
                scope.$index,
                subJsonItems[scope.$index]
              )
            "
            @select="
              setSelectRowData(
                selectedPropMapSub.setProp,
                selectedPropMapSub.setOriginProp,
                selectedPropMapSub.selectedProp,
                scope.$index,
                subJsonItems[scope.$index]
              )
            "
          ></autocomplete-input>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" width="220" min-width="160">
        <template #default="scope">
          <el-input
            v-model="subJsonItems[scope.$index].materialName"
            disabled
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格" width="180" min-width="160">
        <template #default="scope">
          <el-input
            v-model="subJsonItems[scope.$index].specifications"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="型号" width="180" min-width="160">
        <template #default="scope">
          <el-input v-model="subJsonItems[scope.$index].model"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="180" min-width="160">
        <template #default="scope">
          <el-input v-model="subJsonItems[scope.$index].unit"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="180" min-width="160">
        <template #default="scope">
          <el-input v-model="subJsonItems[scope.$index].quantity"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="已完成数量" width="180" min-width="160">
        <template #default="scope">
          <el-input
            v-model="subJsonItems[scope.$index].completedQuantity"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="完成日期" width="250" min-width="160">
        <template #default="scope">
          <el-date-picker
            v-model="subJsonItems[scope.$index].completedTime"
            type="date"
            placeholder="请选择日期"
          />
        </template>
      </el-table-column>
    </template>
  </receipt-core>
</template>

<script lang="ts" setup>
import ReceiptCore from "@/components/receipt/ReceiptCore.vue";
import { provide, ref } from "vue";
import { ReceiptsSub } from "@/models/ReceiptsSub";
import { SelectedPropMap } from "@/components/input/SelectedPropMap";
import AutocompleteInput from "@/components/input/AutocompleteInput.vue";
import { AutocompleteInputEventArray } from "@/components/input/AutocompleteInputEventArray";
import api from "@/utils";
import { AutocompleteInputEvent } from "@/components/input/AutocompleteInputEvent";

//传递到单据表中需要展示的列到ReceiptsTable
const receiptsTableFieldList = [
  {
    filedName: "idJson.productionPlanName",
    label: "所补生产计划名称",
    width: 220,
  },
  {
    filedName: "idJson.productionPlanNoHand",
    label: "所补生产计划编码",
    width: 220,
  },
  {
    filedName: "idJson.planNumber",
    label: "计划总个数",
    width: 220,
  },
  {
    filedName: "idJson.plannedDate",
    label: "计划日期",
    width: 220,
  },
  {
    filedName: "idJson.preparationPerson",
    label: "编制人",
    width: 220,
  },
  {
    filedName: "idJson.preparationDate",
    label: "编制时间",
    width: 220,
  },
];
provide("receiptsTableFieldList", receiptsTableFieldList);

// 数据规范, 表中没有需要规范格式的数据, 则不需要这一行.
const dataFormat = (
  columnName: string,
  cellValue: string,
  callback: (value: string) => void
) => {
  if (
    columnName === "idJson.preparationDate" ||
    columnName === "idJson.plannedDate"
  ) {
    const date = new Date(cellValue);
    const dateFormat = api.formatDate(date, "yyyy年MM月dd日");
    if (dateFormat !== "NaN年aN月aN日") {
      callback(dateFormat);
    }
  }
};
//传递idJson内的内容ReceiptsCore的Dialog内的插槽
const idJsonItems = ref({
  productionPlanName: null,
  productionPlanNoHand: null,
  planNumber: null,
  plannedDate: null,
  preparationPerson: null,
  preparationDate: null,
} as unknown);
provide("idJsonItems", idJsonItems);

//传递subJson内的内容到ReceiptsCore的Dialog内的Table内的插槽
const subJsonItems = ref([
  {
    category: null,
    materialNo: null,
    materialName: null,
    specifications: null,
    model: null,
    unit: null,
    quantity: null,
    completedQuantity: null,
    completedTime: null,
  },
] as Array<unknown>);
// provide("subJsonItems", subJsonItems);

//清空传递idJson内的内容ReceiptsCore的Dialog内的插槽内容
//清空传递subJson内的内容ReceiptsCore的Dialog内的Table内的插槽内容
//远程搜索的数据除外，不用清除，不然无法使用远程搜索
const clearOpenJson = () => {
  idJsonItems.value = {
    planNumber: null,
    plannedDate: null,
    preparationPerson: null,
    preparationDate: null,
  };
  subJsonItems.value = [
    {
      category: null,
      specifications: null,
      model: null,
      unit: null,
      quantity: null,
      completedQuantity: null,
      completedTime: null,
    },
  ];
};

//子组件编辑时将某行idJson传递回本父组件并导入插槽内
//子组件编辑时将某行receiptsSub传递回本父组件，然后取出subJson导入插槽内
const poseEditJson = (idJson: unknown, receiptsSub?: Array<ReceiptsSub>) => {
  idJsonItems.value = idJson;
  if (receiptsSub?.length === undefined || receiptsSub?.length === 0) {
    subJsonItems.value = [
      {
        category: null,
        materialNo: null,
        materialName: null,
        specifications: null,
        model: null,
        unit: null,
        quantity: null,
        completedQuantity: null,
        completedTime: null,
      },
    ];
  } else if (subJsonItems.value.length >= receiptsSub.length) {
    let i = 0;
    for (i; i < receiptsSub.length; i = i + 1) {
      subJsonItems.value[i] = receiptsSub[i].subJson;
    }
  } else {
    let j = subJsonItems.value.length;
    for (j; j < receiptsSub.length; j = j + 1) {
      subJsonItems.value.push({});
    }
    let i = 0;
    for (i; i < receiptsSub.length; i = i + 1) {
      subJsonItems.value[i] = receiptsSub[i].subJson;
    }
  }
};

//提交表单时将最新的ReceiptsSub传来处理，加入subJson后用callback返回
const poseSubmitJson = (
  callback: (value: Array<ReceiptsSub>) => void,
  no: string,
  receiptsSub: Array<ReceiptsSub>
) => {
  if (receiptsSub?.length === 0) {
    subJsonItems.value = [];
  } else {
    let i = 0;
    for (i; i < receiptsSub.length; i = i + 1) {
      receiptsSub[i].subJson = subJsonItems.value[i];
      receiptsSub[i].no = no;
    }
  }
  callback(receiptsSub);
};

const addRowSub = () => {
  subJsonItems.value.push({});
};
const deleteRowSub = (index: number) => {
  subJsonItems.value.splice(index, 1);
};
const jsonFormat = (
  data: Record<string, unknown>[][],
  callback: (value: Record<string, unknown>[]) => void
) => {
  let jsonList: Record<string, unknown>[] = [];
  for (let i = 0; i < data[0].length; i++) {
    // 存入字段名和excel表中的名称的映射，记得修改
    jsonList[i] = {};
    jsonList[i].no = data[0][i]["test1"];
    jsonList[i].name = data[0][i]["test2"];
    jsonList[i].description = data[0][i]["test3"];
    jsonList[i].departmentPhone = data[0][i]["test4"];
    jsonList[i].createUser = sessionStorage.getItem("token") as string;
    jsonList[i].createGmt = new Date();
  }
  callback(jsonList);
};
/**
 * 远程搜索和名称跟随
 */
const selectedPropMap = {
  selectedProp: "productionPlanName",
  selectedOriginProp: "name",
  setProp: "productionPlanNoHand",
  setOriginProp: "noHand",
} as SelectedPropMap;

const { getRecords, setSelectRow } = AutocompleteInputEvent(
  "/receipts/production_plan_receipt",
  idJsonItems,
  selectedPropMap
);
//多个远程搜索用类接收返还，用.属性调用。
//涉及数组时，用封装的数组专用组件，用getRecords完成选择框的内容，返回想要的某个对象，再在本vue内完成赋值。
const selectedPropMapSub = {
  selectedProp: "materialNo",
  selectedOriginProp: "no",
  setProp: "materialName",
  setOriginProp: "name",
} as SelectedPropMap;
const autocompleteInputEventSub = AutocompleteInputEventArray(
  "/receipts/material/autocompleteInput/material",
  selectedPropMapSub
);
const setSelectRowData = (
  setProp: string,
  setOriginProp: string,
  selectedProp: string,
  index: number,
  subJsonItem: Record<string, unknown>
) => {
  subJsonItems.value[index] = autocompleteInputEventSub.setSelectRowData(
    setProp,
    setOriginProp,
    selectedProp,
    subJsonItem
  );
};
</script>

<style scoped></style>
